package clsr.info.blog.service;

import clsr.info.blog.common.api.IArticleService;
import clsr.info.blog.common.entity.Article;
import clsr.info.blog.common.event.ArticleEvent;
import clsr.info.blog.common.event.BaseEvent;
import clsr.info.blog.common.event.EventEnum;
import clsr.info.blog.common.event.EventPublisher;
import clsr.info.blog.repository.ArticleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@Slf4j
public class ArticleServiceImpl extends BaseServiceImpl<Article> implements IArticleService {

  @Autowired private ArticleRepository articleRepository;
  @Autowired @Lazy private EventPublisher eventPublisher;

  @Override
  public Integer saveArticle(Article article) {
    Article saved = articleRepository.save(article);
    return saved.getId();
  }

  @Override
  public Article loadArticle(Integer id) {
    Optional<Article> articleOptional = articleRepository.findById(id);
    eventPublisher.emit(new ArticleEvent(id, ArticleEvent.Type.READ, this.getEventType()));
    return articleOptional.get();
  }

  @Override
  public Page<Article> loadArticleList(Article article, Pageable pageable) {
    Page<Article> pages = articleRepository.findAll(Example.of(article), pageable);
    return pages;
  }

  @Override
  public EventEnum getEventType() {
    return EventEnum.ARTICLE;
  }

  @Override
  public void dealWithEvent(BaseEvent event) {
    ArticleEvent articleEvent = (ArticleEvent) event;
    Integer id = articleEvent.getId();
    Optional<Article> articleOptional = articleRepository.findById(id);
    if (articleOptional.isEmpty()) {
      return;
    }
    Article article = articleOptional.get();
    if (articleEvent.getType().getCode().equals(ArticleEvent.Type.READ.getCode())) {
      article.setReadNum(article.getReadNum() + 1);
    }
    articleRepository.save(article);
  }
}
